import axios from 'axios';
import { useAuthStore } from '../stores/auth';
import { useRouter } from 'vue-router';

let router;

const apiClient = axios.create({
  baseURL: '/api',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
});

apiClient.interceptors.request.use(config => {
  // 优先从 store 获取 token，如果没有则从 localStorage 获取
  const authStore = useAuthStore();
  const token = authStore.token || localStorage.getItem('token');
  
  if (token) {
    config.headers['token'] = token;
    // 如果 token 在 localStorage 中存在但在 store 中不存在，则更新 store
    if (!authStore.token) {
      authStore.setToken(token);
    }
  }
  return config;
});

export function setupInterceptors(routerInstance) {
  router = routerInstance;

  apiClient.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        // Token 过期，清除 token 并跳转到登录页面
        const authStore = useAuthStore();
        authStore.clearToken(); // 这会同时清除 localStorage 中的 token
        if (router) {
          router.push({ name: 'Login' });
        }
      }
      return Promise.reject(error);
    }
  );
}

export default apiClient;